<template>
    <!-- 品牌管理 -->
    <el-card shadow="always" :body-style="{ padding: '20px' }">
        <div>
            <el-form :rules="rules" :inline="false" size="normal">
                <el-form-item>
                    <!-- 添加 -->
                    <el-button type="primary" icon="el-icon-plus" @click="addClear">添加
                    </el-button>
                </el-form-item>
            </el-form>
            <!-- 表格 -->
            <el-table ref="multipleTable" :data="trademark.records" tooltip-effect="dark" style="width: 100%" border
                v-loading="loading">
                <el-table-column label="序号" type="index" width="80" align="center">
                </el-table-column>
                <el-table-column prop="tmName" label="品牌名称" align="center">
                </el-table-column>
                <el-table-column label="品牌LOGO" show-overflow-tooltip align="center">
                    <template slot-scope="Logo">
                        <img :src="Logo.row.logoUrl" alt="" width="100px" height="80px">
                    </template>
                </el-table-column>
                <el-table-column prop="operate" label="操作" show-overflow-tooltip align="center">
                    <template v-slot="{row,$index}">
                        <el-button type="warning" icon="el-icon-edit" @click="updateTrade(row)" size="mini">修改
                        </el-button>
                        <el-popconfirm :title="`确定要删除${row.tmName}？`" @confirm="deleteTradeList(row)"
                            icon="el-icon-delete" type="danger" style="margin-left:10px">
                            <el-button v-if="$hasBP('btn.Trademark.remove')" type="danger" icon="el-icon-delete" slot="reference" size="mini">删除</el-button>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <el-pagination @size-change="handleSizeChange" @current-change="trademarkList" :current-page="currentPage"
                :page-sizes="[3,5,7,9]" :page-size="pageSize" layout=" prev, pager, next, jumper,->,sizes,total"
                :total="total">
            </el-pagination>

            <!-- 公用弹框 -->
            <el-dialog :title="newTrademark.id ? '修改品牌' : '添加品牌'" :visible.sync="dialogFormVisible">
                <el-form :model="newTrademark" :rules="rules" ref="refForm">
                    <!-- 输入框 -->
                    <el-form-item label="品牌名称" :label-width="formLabelWidth" prop="tmName" class="demo-ruleForm">
                        <el-input autocomplete="off" v-model="newTrademark.tmName"></el-input>
                    </el-form-item>
                    <!-- 图像上传 -->
                    <el-form-item label="品牌LOGO" :label-width="formLabelWidth" prop="logoUrl">
                        <el-upload class="avatar-uploader" action="/dev-api/admin/product/upload"
                            :show-file-list="false" :on-success="handleAvatarSuccess"
                            :before-upload="beforeAvatarUpload" v-model="newTrademark.logoUrl">
                            <img v-if="newTrademark.logoUrl" :src="newTrademark.logoUrl" class="avatar">
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                            <div slot="tip">只能上传jpg/png文件，且不超过50kb</div>
                        </el-upload>
                    </el-form-item>
                </el-form>
                <!-- 确定/取消按钮 -->
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取 消</el-button>
                    <el-button type="primary" @click="AddTrade">确 定</el-button>
                </div>
            </el-dialog>
        </div>
    </el-card>


</template>

<script>

import { reqTradeMarkList, reqAddTradeMark, reqUpdateTradeMark, reqDelTradeMark } from '@/api/trademark/trademark'


export default {
    data() {
        return {
            // 分页器--当前页
            currentPage: 1,
            // --一页几条
            pageSize: 3,
            // --总共几条
            total: 0,
            // 品牌列表
            trademark: {},
            // loading 
            loading: false,
            // 弹框显示与隐藏
            dialogTableVisible: false,
            dialogFormVisible: false,
            formLabelWidth: '120px',
            imageUrl: '',
            // 表单验证
            // 收集新增品牌的数据
            newTrademark: {
                tmName: '',
                logoUrl: ''
            },
            // 规则
            rules: {
                tmName: [
                    {
                        required: true,
                        message: '请输入名称',
                        trigger: 'blur'
                    },
                    // 自定义校验规则
                    {
                        // custom: this.verification,
                        message: '请输入正确的名称',
                        trigger: 'blur'  //触发时机--失去焦点
                    },
                    { min: 4, max: 10, message: '长度在 4 到 10个字符', trigger: 'blur' }
                ],
                logoUrl: [
                    {
                        required: true,
                        message: '请上传LOGO',
                        trigger: 'blur',
                    },
                    {
                        // custom: this.verification,
                        message: '请上传正确的图片',
                        trigger: 'blur'  //触发时机--失去焦点
                    }
                ]
            },


        }
    },
    mounted() {
        // 调用品牌的函数 
        this.trademarkList(1)
    },

    methods: {
        // 请求列表的数据 --- 分页器页码
        async trademarkList(page = 1) {
            // 发请求之前；loading开始
            this.loading = true
            // 参数整理
            this.currentPage = page
            let result = await reqTradeMarkList(page, this.pageSize)
            // console.log(result);
            // 存储数据
            this.trademark = result.data
            this.pageSize = result.data.size
            this.currentPage = result.data.current
            this.total = result.data.total
            // 数据加载完成后，loading结束
            this.loading = false
        },

        // 分页器--一页几条
        handleSizeChange(limit) {
            this.pageSize = limit
            this.trademarkList()
        },

        // 删除
        async deleteTradeList(row) {
            try {
                await reqDelTradeMark(row.id)
                // 重新获取列表的数据
                this.trademarkList(this.currentPage)
            } catch (error) {

            }
        },
        // 自定义校验规则
        // value: 需要进行校验的数据值
        // callback: 用来指定校验是否通过的函数, 如果执行没有传递参数代表通过, 如果传递了代表不通过, 
        verification(rule, value, callback) {
            if (value.length < 2 || value.length > 10) {
                callback(new Error('长度必须在2-10个字符之内'))  //不通过
            } else {
                callback() //成功
            }
        },

        // 点击添加按钮
        addClear() {
            this.dialogFormVisible = true
            //每一次对话框显示出来的时候，先清空数据
            this.newTrademark = {
                tmName: '',
                logoUrl: ''
            }
        },

        // 点击修改更新
        async updateTrade(row) {
            this.dialogFormVisible = true

            // 重置初始化，再次重新赋值
            this.newTrademark.id = row.id
            this.newTrademark.tmName = row.tmName
            this.newTrademark.logoUrl = row.logoUrl

        },

        // 点击确定发起请求
        async AddTrade() {
            try {
                this.$refs['refForm'].validate(async (valid) => {
                    console.log(valid)
                    if (valid) {
                        // 证明验证通过

                        if (this.newTrademark.id) {
                            await reqUpdateTradeMark(this.newTrademark)
                            //如果是新增品牌分页器留在当前页
                            this.trademarkList(this.currentPage);
                            // 弹框隐藏
                            this.dialogFormVisible = false
                            //添加成功显示文字信息
                            this.$message({
                                message: '修改品牌成功',
                                type: 'success'
                            });
                            // 重新获取列表的数据
                            this.trademarkList()
                        } else {
                            await reqAddTradeMark(this.newTrademark)
                            //如果是新增品牌分页器留在第一页
                            this.trademarkList();
                            // 弹框隐藏
                            this.dialogFormVisible = false
                            //添加成功显示文字信息
                            this.$message({
                                message: '添加品牌成功',
                                type: 'success'
                            });
                            // 清空数据
                            this.newTrademark = {
                                tmName: '',
                                logoUrl: ''
                            }
                            // 重新获取列表的数据
                            this.trademarkList()
                        }
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });


            } catch (error) {
                console.log(error.message);
                this.$message.error('验证不通过');
            }

           
        },

        // 弹框图片的验证
        handleAvatarSuccess(res, file) {
            this.newTrademark.logoUrl = res.data
        },
        // 图片验证规则
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg' || 'image/jpg' || 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 5;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },





    }

}


</script>

<style scoped>
.avatar-uploader /deep/ .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader /deep/ .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}

.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>